package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
)

// 短信验证请求参数
type SmsReq struct {
	VerifyId string `json:"verify_id" validate:"required" label:"验证id"`    //验证id
	Verify   string `json:"verify" validate:"required" label:"验证码"`        //验证码
	Mobile   string `json:"mobile" validate:"required,mobile" label:"手机号"` //手机号
}

// 短信验证
func SmsVerifyMiddleware(redis *redis.Client) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req SmsReq
		if err := utils.BindAndValid(c, &req); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		data := cache.New(redis).Get(req.VerifyId)
		if data == "" {
			response.Fail(c, "验证码已过期或不存在")
			c.Abort()
			return
		}
		res := conv.StringToObject(data)
		if conv.String(res["mobile"]) != req.Mobile {
			response.Fail(c, "手机号与验证不一致")
			c.Abort()
			return
		}
		if res["verify"] != req.Verify {
			response.Fail(c, "验证码错误")
			c.Abort()
			return
		}
		c.Set("mobile", req.Mobile)
		c.Next()
	}
}
